package controller;

import dao.UserDAO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.User;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 验证用户名和密码
        User user = userDAO.login(username, password);
        if (user != null) {
            // 登录成功，将用户信息存入Session
            request.getSession().setAttribute("loginUser", user);
            // 重定向到仪表盘
            response.sendRedirect(request.getContextPath() + "/DashboardServlet");
        } else {
            // 登录失败，返回登录页并显示错误信息
            request.setAttribute("errorMsg", "用户名或密码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}
